<?php

namespace App\Http\Middleware;

use App\Kit\Token;
use Closure;
use Illuminate\Http\Request;
use stdClass;

class Customer
{
    public function handle(Request $request, Closure $next)
    {
        $uri = substr($request->path(), 9);
        $noAuth = ['login', 'register', 'code/login', 'address', 'upload', 'send/sms', 'pdf'];
        if(in_array($uri, $noAuth)) {
            return $next($request);
        }

        $token = $request->header('token');
        $err = [
            'data' => [],
            'message' => '',
            'code' => 400
        ];
        if(empty($token)) {
            return response()->json($err); 
        }

        $payload = Token::decodeToken($token);
        if(!$payload) {
            return response()->json($err);
        }

        $customer_id = $payload->data->id ?? '';
        if(empty($customer_id)) {
            return response()->json($err);
        }

        $storage_token = Token::get_csutomer_token($customer_id);
        if($token != $storage_token) {
            return response()->json($err);
        }

        $auth = new stdClass;
        $auth->id = $customer_id;
        $auth->name = $payload->data->name;
        $auth->sn = $payload->data->sn;
        $request->attributes->add(['auth' => $auth]);
        return $next($request);
    }

}
